package repository

import (
	"fmt"
	"gluenet/modules/manager/server/adapter/repository/mysql"
	"gluenet/modules/manager/server/domain/dependency"
	"gluenet/modules/manager/server/domain/entity"
	"gluenet/modules/manager/server/infra"
	"gluenet/modules/manager/server/infra/prepare"
	"time"
)

func init() {
	prepare.RegisterRepo(func() {
		repo := NewAgentRepo()
		prepare.InjectDependency(func() dependency.AgentRepo {
			return repo
		})
	})
}

func NewAgentRepo() *Agent {
	r := &Agent{}
	return r
}

type Agent struct {
}

func (a Agent) Get(GUID string) (*entity.Agent, error) {
	var obj []entity.Agent
	if err := mysql.DB.Where(map[string]interface{}{
		"guid": GUID,
	}).Find(&obj); err != nil {
		return nil, err
	}

	if len(obj) > 1 {
		return nil, fmt.Errorf("much primary keys in sql")
	}

	if len(obj) == 0 {
		return nil, infra.DataNotFind
	}

	return &obj[0], nil
}

func (a Agent) FindAll() ([]entity.Agent, error) {
	var obj []entity.Agent
	if err := mysql.DB.Where(map[string]interface{}{}).Find(&obj); err != nil {
		return nil, err
	}
	return obj, nil
}

func (a Agent) FindBy(query map[string]interface{}) ([]entity.Agent, error) {
	//TODO implement me
	var obj []entity.Agent

	if err := mysql.DB.Where(query).Find(&obj); err != nil {
		return nil, err
	}

	if len(obj) == 0 {
		return nil, fmt.Errorf("can't find data")
	}

	//var cfgs = make([]*entity.Config, len(obj))
	//for k, v := range obj {
	//	cfgs[k] = &entity.Config{
	//		Config: v,
	//	}
	//}
	return obj, nil
}

func (a Agent) Add(obj *entity.Agent) (*entity.Agent, error) {
	obj.RegisterTime = time.Now()
	obj.LastConnectTime = time.Now()
	_, err := mysql.DB.InsertOne(obj)
	if err != nil {
		return nil, err
	}
	return obj, err
}

func (a Agent) Del(GUID string) (*entity.Agent, error) {
	var cfg entity.Agent
	_, err := mysql.DB.Where(map[string]interface{}{
		"guid": GUID,
	}).Delete(&cfg)
	if err != nil {
		return nil, err
	}
	return &cfg, nil
}

func (a Agent) Update(obj *entity.Agent) (*entity.Agent, error) {
	obj.LastConnectTime = time.Now()
	_, err := mysql.DB.Where(map[string]interface{}{
		"guid": obj.GUID,
	}).Update(obj)
	if err != nil {
		return nil, err
	}
	return obj, nil
}
